package com.jdrx.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class GwCorsFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// nothing
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse response = (HttpServletResponse) res;
		response.setHeader("Allow", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
		response.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
		response.setHeader("Access-Control-Allow-Methods", req.getHeader("Access-Control-Request-Method"));
		response.setHeader("Access-Control-Max-Age", "3600000");
		response.setHeader("Access-Control-Allow-Headers", req.getHeader("Access-Control-Request-Headers"));
		response.setHeader("Access-Control-Allow-Credentials", "true");
		response.setHeader("Vary", "Origin");
		if (req.getMethod().equals("OPTIONS")) {
			response.setStatus(200);
		} else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {
		// nothing
	}
}